import vnode from './vnode';

/**
 * @description simple version, 3 params needed.
 * @param {String} sel 
 * @param {Object} data 
 * @param {Array<any>|Vnode|String} c 
 * h(ele, {}, '');
 * h(ele, {}, Vnode);
 * h(ele, {}, [...Vnodes]};
 */
export default function h (sel, data, c) {
  if (arguments.length !== 3) {
    throw new Error('Sorry, must give 3 params');
  }

  if (typeof c === 'string' || typeof c === 'number') {

    return vnode(sel, data, undefined, c, undefined);
  } else if (Array.isArray(c)) {

    // h(ele, {}, [...Vnodes]}情况
    // c 传入的是数组，那么必须是对象（调用的时候，如果数组c里面是h()，会执行然后返回Vnode对象）数组
    let children = [];
    
    for (let i = 0, len = c.length; i < len; i++) {
      let it = c[i];
      if (typeof it != 'object' || !it.hasOwnProperty('sel')) {
        throw new Error('第三个参数必须是对象数组');
      }

      children.push(it);
    }

    return vnode(sel, data, children, undefined, undefined);
  } else if (typeof c === 'object' && c.hasOwnProperty('sel')) {
    // h(ele, {}, Vnode); 情况
    
    let children = [c];
    return vnode(sel, data, children, undefined, undefined);
  } else {
    throw new Error('Illegal params'); 
  }
}
